package com.wanho.java159.task.service;

import com.wanho.java159.cb.mapper.ItemMapper;
import com.wanho.java159.cb.mapper.TaskMapper;
import com.wanho.java159.cb.po.Task;
import com.wanho.java159.cb.po.TaskExample;
import com.wanho.java159.common.util.RedisUtil;
import org.aspectj.weaver.AnnotationTargetKind;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
public class TimedTaskService {
    @Resource
    private TaskMapper taskMapper ;
    @Resource
    private ItemMapper itemMapper ;
    @Resource
    private RedisUtil redisUtil ;
    /**
     * 每1分钟执行一次 定时任务，进行查询 cb_task表中数据进行同步到redis中
     */
    @Scheduled(cron = "0 */1 * * * ?")
    @Transactional
    public void item2Redis(){
        System.out.println("=================task  begin=======================");
        //查询cb_task表中 未同步成功 并且同步次数小于最大次数的数据
        List<Task> taskList = taskMapper.selectTaskNeedToSync();
        //循环所有的task
        for (Task task : taskList) {
            //根据类型进行对 redis操作
            System.out.println("=========task===111=======>"+task);
            String taskType = task.getTaskType();
            System.out.println("=========task======222====>"+taskType);
            switch (taskType){
                //新增  修改都 redis来说：都是put redis = map
                case "1":
                case "2":
                    redisUtil.set("cb:item:"+task.getTablePkVal(),itemMapper.selectByPrimaryKey(Long.parseLong(task.getTablePkVal())));
                    break;
                case "3":
                    //删除redis
                    redisUtil.delete("cb:item:"+task.getTablePkVal());
                    break;
            }
            //修改task表
            task.setIsSynchronized(true);
            task.setNumberSynced(task.getNumberSynced()+1);
            task.setIsSuccessed(true);
            taskMapper.updateByPrimaryKeySelective(task) ;
        }
        System.out.println("=================task  end=======================");
    }
}
